import 'dart:math';

import 'package:flame_audio/flame_audio.dart';

import '../../../config/GameUtils.dart';
import '../../../config/AssetsName.dart';
import '../../../audio/AudioHelper.dart';

class SoundManager {
  SoundManager._internal();

  static final SoundManager _instance = SoundManager._internal();

  factory SoundManager() => _instance;

  final List<String> hitSounds = [
    AssetsName.peaHit1,
    AssetsName.peaHit2,
    AssetsName.peaHit3,
  ];
  final Random _random = Random();

  Future<void> loadSounds() async {
    await AudioHelper().loadAll(hitSounds);
  }

  // 豌豆攻击音效
  void playRandomPeaHitSound() {
    final index = _random.nextInt(hitSounds.length);
    AudioHelper().play(hitSounds[index], 4);
  }

  // 收集阳光音效
  void playCollectSunlight() {
    AudioHelper().play(AssetsName.sunlightCollect, 4);
  }

  // 栽种
  void playPlant() {
    AudioHelper().play(AssetsName.plant, 4);
  }

  // 大批僵尸
  void playZombieComing() {
    AudioHelper().play(AssetsName.zombieComing, 4);
  }

  // 脑子被吃了
  void playBrainAte() {
    AudioHelper().play(AssetsName.brainAte, 4);
  }

  // 选择植物
  void playChoosePlant() {
    AudioHelper().play(AssetsName.choosePlant, 4);
  }

  // 只要全局有僵尸在吃就播放吃的声音
  AudioPlayer? _eatingPlayer;
  int nowEatingPlantZombie = 0; // 现在在吃的僵尸

  Future<void> playEatingPlant() async {
    nowEatingPlantZombie++;
    if (nowEatingPlantZombie == 1) {
      _eatingPlayer = await AudioHelper().loop(
        AssetsName.bgmZombieEatingPlant,
        2,
      );
    }
    if (nowEatingPlantZombie <= 0) {
      await _eatingPlayer?.stop();
      _eatingPlayer = null;
    }
    GameUtils.l("当前在吃的僵尸$nowEatingPlantZombie");
  }

  Future<void> stopEatingPlantSound() async {
    if (nowEatingPlantZombie > 0) {
      // 保险措施，防止一些异步出现的问题（比如僵尸刚吃就被干掉了）
      nowEatingPlantZombie--;
    }
    if (nowEatingPlantZombie <= 0) {
      await _eatingPlayer?.stop();
      _eatingPlayer = null;
    }
    GameUtils.l("当前在吃的僵尸$nowEatingPlantZombie");
  }

  Future<void> playAtePlant() async {
    await AudioHelper().play(AssetsName.bgmAtePlant, 3);
  }

  void initMusic() {
    AudioHelper().init();
    loadSounds();
  }

  // 初始化战斗音乐
  void initFightMusic() {
    AudioHelper().playBgm(AssetsName.bgmGrassWalk, 1);
  }

  // 选择种子
  void initChooseSeeds() {
    AudioHelper().playBgm(AssetsName.bgmChooseYourSeeds, 1);
  }

  // 选择植物种子
  void choosePlantSeed() {
    AudioHelper().play(AssetsName.choosePlantSeed, 4);
  }

  // 停止播放
  void stop() {
    AudioHelper().stop();
  }
}
